﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Globalization;

using JohnnySins.DAL;
using JohnnySins.DAL.Repositories;
using JohnnySins.Entities;
using JohnnySins.Code;
using System.Web.Services;

namespace JohnnySins.Admin
{
    public partial class MyPhotoSets : System.Web.UI.Page
    {
        public string JsCodeToRunOnReady { get; set; }

        protected void Page_Load(object sender, EventArgs e)
        {
            FindSelected();

            if (!IsPostBack)
            {
                LoadPhotoSet();
            }
        }
        public int[] Selected { get; set; }

        private void FindSelected()
        {
            var selected = new List<int>();

            foreach (GridViewRow row in grid.Rows)
            {
                if (row.RowType == DataControlRowType.DataRow)
                {
                    var check = row.Cells[0].FindControl("cbSelected") as CheckBox;
                    if (check.Checked)
                    {
                        var id = row.FindControl("hidId") as HiddenField;
                        selected.Add(int.Parse(id.Value));
                    }
                }
            }

            Selected = selected.ToArray();
        }

        protected void LoadPhotoSet()
        {
            using (var repo = RepositoryFactory.ResolveRepository<PhotoSetRepository>())
            {
                grid.DataSource = repo.FindAll();
                grid.DataBind();
            }
        }

        protected void grid_RowDataBound(Object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                PhotoSet item = (PhotoSet)e.Row.DataItem;

                ImageButton ibtn = (ImageButton)e.Row.FindControl("btnDeactivate");
                ibtn.Visible = item.IsActive;

                ibtn = (ImageButton)e.Row.FindControl("btnActivate");
                ibtn.Visible = !item.IsActive;

                CheckBox cbSelected = (CheckBox)e.Row.FindControl("cbSelected");
                cbSelected.Checked = Selected.Contains(item.PhotoSetId);
            }

            if (e.Row.RowType == DataControlRowType.Header)
            {
                CheckBox chbAll = (CheckBox)e.Row.FindControl("chbAll");
                chbAll.Checked = (Selected.Length == (grid.DataSource as IEnumerable<PhotoSet>).Count());
            }
        }

        protected void grid_Command(object sender, CommandEventArgs e)
        {
            int id = Convert.ToInt32(e.CommandArgument.ToString());

            if (e.CommandName == "delete")
            {
                DeletePhotoSet(id);
            }
            else
            {
                using (var repo = RepositoryFactory.ResolveRepository<PhotoSetRepository>())
                {
                    switch (e.CommandName)
                    {
                        case "deactivate":
                            repo.Deactivate(id);
                            break;
                        case "activate":
                            repo.Activate(id);
                            break;
                    }
                }
            }

            LoadPhotoSet();
        }

        protected void rptPhotos_ItemCommand(Object Sender, RepeaterCommandEventArgs e)
        {
            string[] commandArgs = e.CommandArgument.ToString().Split(new char[] { ',' });
            int setId = Convert.ToInt32(commandArgs[0]);
            int photoId = Convert.ToInt32(commandArgs[1]);

            if (e.CommandName == "deletePhoto")
            {
                DeletePhoto(setId, photoId);
                LoadPhotos();
                LoadPhotoSet();
                upPhotoSet.Update();
            }
        }

        protected void rptPhotos_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                PhotoSetPhoto rowView = e.Item.DataItem as PhotoSetPhoto;

                Image img = e.Item.FindControl("imgPhoto") as Image;
                img.ImageUrl = string.Format("~/Files/PhotoSets/{0}/{1}", rowView.PhotoSetId.ToString(), rowView.PhysFileName);

                HtmlInputCheckBox chb = e.Item.FindControl("chbIsMember") as HtmlInputCheckBox;
                chb.Attributes.Add("onchange", string.Format("SetFlagValue({0}, this.checked, 1);", rowView.PhotoSetPhotoId.ToString()));

                chb = e.Item.FindControl("chbIsPublic") as HtmlInputCheckBox;
                chb.Attributes.Add("onchange", string.Format("SetFlagValue({0}, this.checked, 2);", rowView.PhotoSetPhotoId.ToString()));

                chb = e.Item.FindControl("chbIsMemberPoster") as HtmlInputCheckBox;
                chb.Attributes.Add("onchange", string.Format("SetFlagValue({0}, this.checked, 3);", rowView.PhotoSetPhotoId.ToString()));

                chb = e.Item.FindControl("chbIsPublicPoster") as HtmlInputCheckBox;
                chb.Attributes.Add("onchange", string.Format("SetFlagValue({0}, this.checked, 4);", rowView.PhotoSetPhotoId.ToString()));
            }
        }

        protected void upDetails_Load(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(Request["__EVENTARGUMENT"]))
            {
                hdId.Text = Request["__EVENTARGUMENT"];

                if (hdId.Text != "-1")
                {
                    using (var repo = RepositoryFactory.ResolveRepository<PhotoSetRepository>())
                    {
                        lblDialogTitle.Text = "EDIT MY PHOTOSET";
                        PhotoSet itm = repo.Find(Convert.ToInt32(hdId.Text));
                        txtPhotoSetTitle.Text = itm.PhotoSetTitle;
                        txtPhotoSetDate.Text = itm.PhotoSetDate == null ? "" : itm.PhotoSetDate.Value.ToString("d", new CultureInfo("en-US"));
                        txtPhotoStarring.Text = itm.PhotoSetStarring;
                        txtPhotoDescription.Text = itm.PhotoSetDescription;
                        chbIsMemberPS.Checked = itm.IsMember;
                        chbIsPublicPS.Checked = itm.IsPublic;

                        rptPhotos.DataSource = itm.Photos;
                        rptPhotos.DataBind();
                    }

                    divFiles.Style["display"] = "block";
                }
                else
                {
                    lblDialogTitle.Text = "ADD NEW MY PHOTOSET";

                    txtPhotoSetTitle.Text = "";
                    txtPhotoSetDate.Text = "";
                    txtPhotoStarring.Text = "";
                    txtPhotoDescription.Text = "";
                    chbIsMemberPS.Checked = true;
                    chbIsPublicPS.Checked = false;

                    divFiles.Style["display"] = "none";
                    rptPhotos.DataSource = new List<PhotoSetPhoto>();
                    rptPhotos.DataBind();
                }
                
                ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "ShowEdit", "$('#editDialog').dialog('open');", true);
            }
        }

        protected void LoadPhotos()
        {
            using (var repo = RepositoryFactory.ResolveRepository<PhotoSetRepository>())
            {
                rptPhotos.DataSource = repo.Find(Convert.ToInt32(hdId.Text)).Photos;
                rptPhotos.DataBind();
            }
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            PhotoSet itm = new PhotoSet();
            itm.PhotoSetTitle = txtPhotoSetTitle.Text;
            itm.PhotoSetDescription = txtPhotoDescription.Text;
            itm.PhotoSetStarring = txtPhotoStarring.Text;
            if (!string.IsNullOrEmpty(txtPhotoSetDate.Text))
                itm.PhotoSetDate = DateTime.ParseExact(txtPhotoSetDate.Text, "d", new CultureInfo("en-US"));
            itm.IsActive = true;
            itm.IsMember = chbIsMemberPS.Checked;
            itm.IsPublic = chbIsPublicPS.Checked;
            
            using (var repo = RepositoryFactory.ResolveRepository<PhotoSetRepository>())
            {
                if (hdId.Text == "-1")
                {
                    repo.Insert(itm);
                    hdId.Text = itm.PhotoSetId.ToString();
                    divFiles.Style["display"] = "block";
                }
                else
                {
                    itm.PhotoSetId = Convert.ToInt32(hdId.Text);
                    repo.Update(itm);

                    ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "HideFieldDialog", "$('#editDialog').dialog('close');", true);
                }
            }
            
            LoadPhotoSet();
            upPhotoSet.Update();
        }

        protected void DeletePhotoSet(int id)
        {
            using (var repo = RepositoryFactory.ResolveRepository<PhotoSetRepository>())
            {
                PhotoSet itm = repo.Find(id);
                if (itm != null)
                {
                    foreach (PhotoSetPhoto subItm in itm.Photos)
                        DeletePhoto(itm.PhotoSetId, subItm.PhotoSetPhotoId);
                    repo.Delete(id);
                }
            }
            LoadPhotoSet();
        }

        protected void DeletePhoto(int setId, int photoId)
        {
            using (var repo = RepositoryFactory.ResolveRepository<PhotoSetRepository>())
            {
                PhotoSetPhoto itm = repo.FindPhoto(setId, null, null).Where(p => p.PhotoSetPhotoId == photoId).SingleOrDefault();
                if (itm != null)
                {
                    repo.DeletePhoto(itm.PhotoSetPhotoId);

                    string path = Path.Combine(Server.MapPath("~/Files/PhotoSets"), setId.ToString(), itm.PhysFileName);
                    if (File.Exists(path))
                        try
                        {
                            File.Delete(path);
                        }
                        catch (Exception ex) { }
                }
            }
        }

        protected void btnDeleteSelected_Click(object sender, EventArgs e)
        {
            using (var repo = RepositoryFactory.ResolveRepository<PhotoSetRepository>())
            {
                foreach (int id in Selected)
                {
                    DeletePhotoSet(id);
                }
            }

            LoadPhotoSet();
        }

        protected void btnActivateSelected_Click(object sender, EventArgs e)
        {
            using (var repo = RepositoryFactory.ResolveRepository<PhotoSetRepository>())
            {
                foreach (int id in Selected)
                {
                    repo.Activate(id);
                }
            }

            LoadPhotoSet();
        }

        protected void btnDeactivateSelected_Click(object sender, EventArgs e)
        {
            using (var repo = RepositoryFactory.ResolveRepository<PhotoSetRepository>())
            {
                foreach (int id in Selected)
                {
                    repo.Deactivate(id);
                }
            }

            LoadPhotoSet();
        }

        protected void btnReverseSelected_Click(object sender, EventArgs e)
        {
            var otherScenes = new List<int>();

            using (var repo = RepositoryFactory.ResolveRepository<PhotoSetRepository>())
            {
                foreach (var scene in repo.FindAll())
                {
                    if (!Selected.Contains(scene.PhotoSetId))
                    {
                        otherScenes.Add(scene.PhotoSetId);
                    }
                }
            }

            Selected = otherScenes.ToArray();
            LoadPhotoSet();
        }

        protected void chbAll_CheckChanged(Object sender, EventArgs e)
        {
            bool chk = (sender as CheckBox).Checked;
            if (chk)
            {
                var other = new List<int>();
                using (var repo = RepositoryFactory.ResolveRepository<PhotoSetRepository>())
                {
                    foreach (var scene in repo.FindAll())
                        other.Add(scene.PhotoSetId);
                }

                Selected = other.ToArray();
            }
            else
                Selected = new int[] { };

            LoadPhotoSet();
        }

        [WebMethod]
        public static string SetFlagValue(int id, int value, int flagId)
        {
            using (var repo = RepositoryFactory.ResolveRepository<PhotoSetRepository>())
            {
                string nameFlag = "";
                switch (flagId)
                {
                    case 1:
                        nameFlag = "IsMember";
                        break;
                    case 2:
                        nameFlag = "IsPublic";
                        break;
                    case 3:
                        nameFlag = "IsMemberPoster";
                        break;
                    case 4:
                        nameFlag = "IsPublicPoster";
                        break;
                }

                repo.SetPhotoFlag(id, nameFlag, value == 1);
                return "1";
            }
            
        }
    }
}